const path = require("path");
const fs = require("fs");
const common = require("./common");
const appendErrorLog = require("./error");
const rootPath = require("../utils/rootPath");

const LOG_DIR = path.join(rootPath, './logs');
const queue = [];
let deals = {
  log: common.append,
  error: appendErrorLog,
}

const logger = {
  init() {
    this.validDir();
    common.init();
  },

  validDir() {
    !fs.existsSync(LOG_DIR) && fs.mkdirSync(LOG_DIR);
  },

  register(types) {
    deals = Object.assign(deals, types)
  },

  loop() {
    let msg;
    while (msg = queue.shift()) {
      const deal = deals?.[msg.type];

      if (!deal) continue;

      if (deal(msg.message) === false) {
        queue.push(msg);
        // if(typeof this.loop === "function"){
        //   setImmediate(this.loop);
        // }else {
        //   console.error('this.loop 异常，接收到的值不是一个函数：' + typeof this.loop);
        // }
        // break;
      }
    }
  },

  addTask(msg) {
    if (!msg) return;

    if (Array.isArray(msg)) {
      msg.forEach(m => this.addTask(m))
      return;
    }

    if (typeof msg === 'string' || typeof msg === "number") {
      msg = {
        type: 'log',
        message: msg
      }
    }

    queue.push(msg);
    queue.length === 1 && this.loop();
  }
}

module.exports = logger
